/*
 * @Author: your name
 * @Date: 2020-12-18 09:54:44
 * @LastEditTime: 2021-02-03 09:51:25
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \web-node-service\routes\login.js
 */
const router = require('koa-router')();
const fs = require('fs');
const path = require('path');
const {getRequestParams} = require('../utils/utils');

// 文件上传
router.post('/upload', async (ctx) => {
    const params = getRequestParams(ctx);
    const filePath = params.files.file.path;
    const name = (params.files.file.name || '').split('.')[0];
    var type = (params.files.file.name || '').split('.')[1];
    const uploadName = `${name}-${new Date().getTime()}.${type}`;

    const fileReader = fs.createReadStream(filePath); // 读取流
    const savePath = path.join(__dirname, '../public/upload/');
    const fileResource = savePath + uploadName;
    const writeStream = fs.createWriteStream(fileResource);
    
    await fileReader.pipe(writeStream);
    
    ctx.success('上传成功', {
        url: `/upload/${name}-${new Date().getTime()}.${type}`,
    });
    
})

module.exports = router;
